// \u4e00-\u9fa5] 中文验证规则
import wxValidate from 'wechat-validate'
Page({
  behaviors: [wxValidate],
  rules: {
    name: [
      { required: true, message: '业主姓名不能为空!' },
      { pattern: /^[\u4e00-\u9fa5]{2,5}$/, message: '业主姓名只能为中文!' },
    ],
    mobile: [
      { required: true, message: '业主手机号不能为空!' },
      { pattern: /^1[3-8]\d{9}$/, message: '请填写正确的手机号!' },
    ],
    idcardFrontUrl: [
      { required: true, message: '请上传身份证国徽面!' }
    ],
    idcardBackUrl: [
      { required: true, message: '请上传身份证照片面!' }
    ]
  },
  data:{
    name:'',
    gender:'1',
    mobile:'',
    point:'',
    building:'',
    room:'',
    idcardFrontUrl: '',
    idcardBackUrl: '',
  },
	onLoad({point, building, room,id}) {
    if(id) this.getHouseDetail(id)
    wx.setNavigationBarTitle({
      title:id? '编辑房屋信息':'添加房屋信息'
    })
    // 获取房屋信息数据
    this.setData({point, building, room})
  },
  async getHouseDetail(id){
    const {code,data}=await wx.http.get('/room/' + id)
    if (code !== 10000) return wx.utils.toast('数据失败!')
    this.setData(data)
  },
  async submitForm(){
    if(!this.validate()) return
     // 获取全部的数据（剔除可能多余参数 __webviewId__）
     // eslint-disable-next-line no-unused-vars
     const { __webviewId__,...data } = this.data
     // 调用接口
     const { code } = await wx.http.post('/room', data)
     // 检测接口是否调用成功
     if (code !== 10000) return wx.utils.toast('提交数据失败!')
    // 返回房屋列表页面
    wx.navigateBack({ delta:this.data.id? 2:4 })
  },
  async uploadPicture(ev){
    console.log(ev);
    const type=ev.mark.type
    try{
      const media = await wx.chooseMedia({
        count: 1,
        mediaType: ['image'],
        sizeType: ['compressed'],
      })
      wx.uploadFile({
        filePath: media.tempFiles[0].tempFilePath,
        name: 'file',
        url: wx.http.baseURL + '/upload',
        header:{
          Authorization: 'Bearer ' + getApp().token,
        },
        success:(res)=>{
          const data=JSON.parse(res.data)
          if(data.code!==10000) return wx.utils.toast('上传图片失败!')
          this.setData({[type]:data.data.url})
      }
      })
    }catch(err){
      console.log(err);
    }
  },
  removePicture(ev){
    const type=ev.mark.type
    if(type){
      this.setData({[type]:''})
    }
  }
})
